package com.borya.core;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.borya.service.impl.BaseServiceImpl;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.borya.constant.RedisConstant;
import com.borya.dao.SdkNotifyDAO;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.model.db.ModelInfo;
import com.borya.model.db.SdkDeviceConf;
import com.borya.model.db.SdkMerchant;
import com.borya.model.db.SdkMerchantAccount;
import com.borya.util.StringUtil;

@Component("redisNotify")
public class RedisNotify extends BaseServiceImpl {

	private Logger log = Logger.getLogger(getClass());

	@Autowired("sdkNotifyDAO")
	private SdkNotifyDAO sdkNotifyDAO;

	public SdkNotifyDAO getSdkNotifyDAO() {
		return sdkNotifyDAO;
	}

	public void setSdkNotifyDAO(SdkNotifyDAO sdkNotifyDAO) {
		this.sdkNotifyDAO = sdkNotifyDAO;
	}

	public void process() {
		List<String> list;
		while (true) {
			final long curTime = System.currentTimeMillis();
			list = getSdkNotifyDAO().brpop(RedisConstant.SDK_OPEN_ACCOUNT);
			if (list != null && list.size() > 0) {
				try {
					processOpenAccount(list, curTime);
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
			}

			// list = getSdkNotifyDAO().brpop(RedisConstant.SDK_MODIFY_ACCOUNT);
			// if(list != null && list.size() > 0){
			// try {
			// processModifyAccount(list, curTime);
			// } catch (Exception e) {
			// log.error(e.getMessage(), e);
			// }
			// }

			sleep(10);
		}
	}

	private void processOpenAccount(List<String> list, long curTime) {
		// {“appId”:”xxx”,”deviceId”:”xxx”,”packageName”:”xxx” }
		log.info("LPUSH," + list);
		for (String val : list) {
			if (!val.startsWith("{")) {
				continue;
			}
			JSONObject json = JSONObject.parseObject(val);
			final String appId = json.getString("appId");
			// 此时deviceId一定是为空的
//			final String deviceId = json.getString("deviceId");
//			final String packageName = json.getString("packageName");

			final String defalutDealerId = "sdk";
			final String packageId = "sdk_default";
			Object[] obj = getSdkNotifyDAO().get(appId, defalutDealerId,
					packageId);
			if (obj == null || obj.length == 0) {
				log.error("Unknow appId,ignore data," + val);
				continue;
			}
			final SdkMerchant merchant = (SdkMerchant) obj[0];
			final ModelInfo info = (ModelInfo) obj[1];
			final SdkDeviceConf conf = (SdkDeviceConf) obj[2];
			log.info("ModelInfo=," + info);

			// create DealerId
			String result = geDealerId(merchant.getCompanyName(),
					merchant.getUserName(), merchant.getPhone());
			// String result =
			// "{\"code\":\"success\",\"dealerId\":\"testDealerId\"}";
			if (result == null || result.trim().length() == 0) {
				log.info("获取dealerId失败," + val);
				continue;
			}
			JSONObject rJso = JSONObject.parseObject(result);
			if (!"200".equals(rJso.getString("code"))) {
				log.info("获取dealerId失败," + val);
				continue;
			}
			final String dealerId = rJso.getJSONObject("data").getString("dealerId");
			log.info("dealerId=," + dealerId);

			SdkMerchantAccount account = new SdkMerchantAccount();
			account.setAppId(appId);
			account.setCreateTime(curTime);
			account.setCredit(0);
			account.setDealerId(dealerId);
			account.setFreezeFee(0);
			account.setLeftFee(0);
			account.setOverDraft(0);

			merchant.setModifyTime(curTime);
			merchant.setDealerId(dealerId);
			merchant.setPopChannel(defalutDealerId);
			if (info != null && info.getDealerId() != null) {
				merchant.setPhoneModel(info.getPhoneModel());
				merchant.setDiscountModel(info.getDiscountModel());
			} else {
				merchant.setPhoneModel("");
				merchant.setDiscountModel("");
			}

			SdkDeviceConf sConf = new SdkDeviceConf();
			sConf.setDeviceId("");
			sConf.setPackageId(makePackageId());
			sConf.setIccidModel(conf.getIccidModel());
			sConf.setAppId(appId);
			
			boolean bool = getSdkNotifyDAO().savebatch(account, merchant, sConf);
			if (bool) {
				continue;
			}
			log.error("Save data to DB error," + val);
		}
	}

	private String makePackageId() {
		return new SimpleDateFormat("yyMMdd").format(new Date())
				+ StringUtil.randomNumberString(6);
	}

	// private void processModifyAccount(List<String> list,long curTime) {
	// for(String val : list){
	// if(!val.startsWith("{")){
	// continue;
	// }
	// JSONObject json = JSONObject.parseObject(val);
	// log.info("add account ="+json);
	// final String appId = json.getString("appId");
	// final String packageId = json.getString("packageId");
	// final String deviceId = json.getString("deviceId");
	//
	//
	// SdkDeviceConf conf = getSdkNotifyDAO().getDeviceConf(packageId);
	// log.info("SdkDeviceConf:"+conf);
	// if(conf == null || conf.getPackageId() == null){
	// log.error("DB not found data by packageId and deviceId,"+val);
	// continue;
	// }
	//
	// if(conf.getFlag() == SdkDeviceConf.Flag.USED){
	// log.info("packageId already userd,packageId="+packageId);
	// continue;
	// }
	// if(conf.getPrice() == 0L){
	// log.info("packageId price is 0,ignore add balance,packageId="+packageId);
	// continue;
	// }
	//
	// conf.setFlag(SdkDeviceConf.Flag.USED);
	// conf.setAppId(appId);
	//
	// SdkMerchantAccount account = new SdkMerchantAccount();
	// account.setAppId(appId);
	// account.setLeftFee(conf.getPrice());
	//
	// log.info("SdkMerchantAccount:"+account);
	//
	// boolean bool = getSdkNotifyDAO().modifyAccount(account, conf);
	// if(bool){
	// continue;
	// }
	// log.error("Save data to DB error,"+val);
	// }
	// }

	private void sleep(int seconds) {
		try {
			TimeUnit.SECONDS.sleep(seconds);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}